<template>
  <el-card>
    <h2>加盟商信息提交</h2>
    <!-- 证件信息上传 -->
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <!-- ...证件信息表单项，略，和你原来一样... -->
      <el-form-item label="门店名称" prop="storeName">
        <el-input v-model="form.storeName" />
      </el-form-item>
      <el-form-item label="营业执照" prop="businessLicenseArr">
        <UploadImage v-model="form.businessLicenseArr" :limit="1" />
      </el-form-item>
      <el-form-item label="食品许可" prop="foodLicenseArr">
        <UploadImage v-model="form.foodLicenseArr" :limit="1" />
      </el-form-item>
      <el-form-item label="手持身份证正反面" prop="idcardHandArr">
        <UploadImage v-model="form.idcardHandArr" :limit="2" />
      </el-form-item>
      <el-form-item label="身份证正反面" prop="idcardArr">
        <UploadImage v-model="form.idcardArr" :limit="2" />
      </el-form-item>
      <el-form-item label="门头照片" prop="storeFrontPhotoArr">
        <UploadImage v-model="form.storeFrontPhotoArr" :limit="1" />
      </el-form-item>
      <el-form-item label="店内环境照片" prop="storeInsidePhotosArr">
        <UploadImage v-model="form.storeInsidePhotosArr" :limit="5" multiple />
      </el-form-item>
      <el-form-item label="门店联系电话" prop="storePhone">
        <el-input v-model="form.storePhone" />
      </el-form-item>
      <el-form-item label="银行卡号" prop="bankCardNumber">
        <el-input v-model="form.bankCardNumber" />
      </el-form-item>
      <el-form-item label="结算手机号" prop="bankPhone">
        <el-input v-model="form.bankPhone" />
      </el-form-item>
      <el-form-item>
        <el-button 
          type="primary" 
          @click="onUploadAll"
          :loading="isUploading"
          :disabled="isUploading || uploadAllSuccess || !canUploadBasicInfo"
        >
          {{ isUploading ? '上传中...' : (uploadAllSuccess ? '已上传' : '上传证件信息') }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-divider>建店照片上传</el-divider>

    <!-- 建店照片上传（合并分区） -->
    <el-card style="margin-top: 20px;">
      <h3>建店照片</h3>
      <el-card style="margin-bottom: 16px;">
        <h4>外卖建店照片</h4>
        <div v-for="type in [0,2,3]" :key="type" style="margin-bottom: 10px;">
          <span>{{ getPhotoTypeLabel(type) }}</span>
          <el-upload
            :file-list="allSetupPhotos[type]"
            :limit="5"
            :on-change="files => handleAllSetupPhotoChange(type, files)"
            :auto-upload="false"
            :disabled="!uploadAllSuccess"
            multiple
            accept="image/*"
            list-type="picture-card"
          >
            <el-button :disabled="!uploadAllSuccess">上传</el-button>
          </el-upload>
        </div>
        <el-button 
          type="primary" 
          style="margin-top: 10px;"
          :disabled="!uploadAllSuccess"
          @click="uploadWaimaiPhotos"
        >上传外卖建店照片</el-button>
      </el-card>
      <el-card>
        <h4>团购建店照片</h4>
        <div v-for="type in [1,4]" :key="type" style="margin-bottom: 10px;">
          <span>{{ getPhotoTypeLabel(type) }}</span>
          <el-upload
            :file-list="allSetupPhotos[type]"
            :limit="5"
            :on-change="files => handleAllSetupPhotoChange(type, files)"
            :auto-upload="false"
            :disabled="!uploadAllSuccess"
            multiple
            accept="image/*"
            list-type="picture-card"
          >
            <el-button :disabled="!uploadAllSuccess">上传</el-button>
          </el-upload>
        </div>
        <el-button 
          type="primary" 
          style="margin-top: 10px;"
          :disabled="!uploadAllSuccess"
          @click="uploadTuangouPhotos"
        >上传团购建店照片</el-button>
      </el-card>
    </el-card>

    <!-- 确认交接 -->
    <el-divider />
    <el-form-item label="下一个交接人" v-if="mustSelectNextUser">
      <el-select v-model="nextUser" placeholder="请选择下一个交接人" style="width: 200px;">
        <el-option v-for="user in nextUserList" :key="user.value" :label="user.label" :value="user.value" />
      </el-select>
    </el-form-item>
    <el-button 
      type="success"
      :disabled="!canConfirmUpload"
      @click="handleConfirmHandover"
    >确认完成上传</el-button>
    <span v-if="handoverConfirmed" style="color: green; margin-left: 8px;">已交接</span>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import UploadImage from '@/components/UploadImage.vue';
import { useUserStore } from '@/store/user';

const userStore = useUserStore();
const userId = computed(() => {
  // 你可以根据实际token解析
  return parseUserIdFromToken(userStore.token);
});

// 证件信息表单
const formRef = ref();
const form = ref({
  storeName: '',
  businessLicenseArr: [],
  foodLicenseArr: [],
  idcardHandArr: [],
  idcardArr: [],
  storeFrontPhotoArr: [],
  storeInsidePhotosArr: [],
  storePhone: '',
  bankCardNumber: '',
  bankPhone: '',
});
const rules = {
  storeName: [{ required: true, message: '请输入门店名称' }],
  businessLicenseArr: [{ required: true, type: 'array', min: 1, message: '请上传营业执照' }],
  foodLicenseArr: [{ required: true, type: 'array', min: 1, message: '请上传食品许可' }],
  idcardHandArr: [{ required: true, type: 'array', min: 2, message: '请上传手持身份证正反面（2张）' }],
  idcardArr: [{ required: true, type: 'array', min: 2, message: '请上传身份证正反面（2张）' }],
  storeFrontPhotoArr: [{ required: true, type: 'array', min: 1, message: '请上传门头照片' }],
  storeInsidePhotosArr: [{ required: true, type: 'array', min: 1, message: '请上传店内环境照片' }],
  storePhone: [{ required: true, message: '请输入联系电话' }],
  bankCardNumber: [{ required: true, message: '请输入银行卡号' }],
  bankPhone: [{ required: true, message: '请输入结算手机号' }],
};
const isUploading = ref(false);
const uploadAllSuccess = ref(false);

// 建店照片上传
const waimaiPhotoTypes = [0, 2, 3];
const tuangouPhotoTypes = [1, 4];
const waimaiPhotos = ref({ 0: [], 2: [], 3: [] });
const tuangouPhotos = ref({ 1: [], 4: [] });

// 合并建店照片数据结构
const allSetupPhotos = ref({ 0: [], 1: [], 2: [], 3: [], 4: [] });

// 处理合并上传区的文件变化
function handleAllSetupPhotoChange(type, files) {
  allSetupPhotos.value[type] = files;
}

// 上传所有建店照片
async function uploadAllSetupPhotos() {
  if (!userId.value) {
    ElMessage.error('请先登录');
    return;
  }
  if (!uploadAllSuccess.value) {
    ElMessage.error('请先上传证件信息');
    return;
  }
  let hasPhoto = false;
  for (const type of [0,1,2,3,4]) {
    const files = allSetupPhotos.value[type] || [];
    for (const file of files) {
      if (!file.url && file.raw) {
        hasPhoto = true;
        const fd = new FormData();
        fd.append('userId', userId.value);
        fd.append('photoType', type);
        fd.append('file', file.raw);
        await fetch('http://121.43.176.9:8090/api/store-setup-photos/upload', {
          method: 'POST',
          body: fd,
        });
      }
    }
  }
  if (hasPhoto) {
    ElMessage.success('建店照片上传完成');
    await fetchSetupPhotos();
  } else {
    ElMessage.info('没有需要上传的建店照片');
  }
}

// 读取所有已上传建店照片
async function fetchSetupPhotos() {
  if (!userId.value) return;
  const res = await fetch(`http://121.43.176.9:8090/api/store-setup-photos/user/${userId.value}`).then(r => r.json());
  if (res.code === 200 && Array.isArray(res.data)) {
    // 先清空
    allSetupPhotos.value = { 0: [], 1: [], 2: [], 3: [], 4: [] };
    res.data.forEach(p => {
      if (allSetupPhotos.value[p.photoType]) {
        allSetupPhotos.value[p.photoType].push({
          name: p.photoPath.split('/').pop(),
          url: p.photoPath,
          status: 'success'
        });
      }
    });
  }
}

// 交接人（可根据实际接口获取）
const nextUserList = [
  { label: '员工A', value: 'employeeA' },
  { label: '员工B', value: 'employeeB' },
];
const nextUser = ref('');
// 只要有建店照片就必须选择交接人
const mustSelectNextUser = computed(() => {
  return [0,1,2,3,4].some(type => (allSetupPhotos.value[type] && allSetupPhotos.value[type].length > 0));
});

// 提交状态
const waimaiSubmitted = ref(false);
const tuangouSubmitted = ref(false);
const handoverConfirmed = ref(false);

// storeId 需在证件信息上传成功后由后端返回
const storeId = ref(null);

const route = useRoute();
storeId.value = route.query.storeId ? Number(route.query.storeId) : null;

// 证件信息上传
async function onUploadAll() {
  if (isUploading.value) return;
  isUploading.value = true;
  try {
    // 手动验证所有必需字段
    const validationErrors = [];
    
    if (!form.value.storeName) {
      validationErrors.push('门店名称');
    }
    if (!form.value.businessLicenseArr || form.value.businessLicenseArr.length === 0) {
      validationErrors.push('营业执照');
    }
    if (!form.value.foodLicenseArr || form.value.foodLicenseArr.length === 0) {
      validationErrors.push('食品许可');
    }
    if (!form.value.idcardHandArr || form.value.idcardHandArr.length < 2) {
      validationErrors.push('手持身份证正反面（需要2张）');
    }
    if (!form.value.idcardArr || form.value.idcardArr.length < 2) {
      validationErrors.push('身份证正反面（需要2张）');
    }
    if (!form.value.storeFrontPhotoArr || form.value.storeFrontPhotoArr.length === 0) {
      validationErrors.push('门头照片');
    }
    if (!form.value.storeInsidePhotosArr || form.value.storeInsidePhotosArr.length === 0) {
      validationErrors.push('店内环境照片');
    }
    if (!form.value.storePhone) {
      validationErrors.push('门店联系电话');
    }
    if (!form.value.bankCardNumber) {
      validationErrors.push('银行卡号');
    }
    if (!form.value.bankPhone) {
      validationErrors.push('结算手机号');
    }
    
    if (validationErrors.length > 0) {
      ElMessage.error(`请完成以下信息填写：${validationErrors.join('、')}`);
      isUploading.value = false;
      return;
    }
    
    // 构建FormData
    const fd = new FormData();
    fd.append('userId', userId.value);
    fd.append('businessLicenseFile', form.value.businessLicenseArr[0]?.raw);
    fd.append('foodLicenseFile', form.value.foodLicenseArr[0]?.raw);
    fd.append('idcardHandFrontFile', form.value.idcardHandArr[0]?.raw);
    fd.append('idcardHandBackFile', form.value.idcardHandArr[1]?.raw);
    fd.append('idcardFrontFile', form.value.idcardArr[0]?.raw);
    fd.append('idcardBackFile', form.value.idcardArr[1]?.raw);
    fd.append('storePhone', form.value.storePhone);
    fd.append('storeFrontPhotoFile', form.value.storeFrontPhotoArr[0]?.raw);
    (form.value.storeInsidePhotosArr || []).forEach((f) => {
      fd.append('storeInsidePhotoFiles', f.raw);
    });
    fd.append('bankCardNumber', form.value.bankCardNumber);
    fd.append('bankPhone', form.value.bankPhone);
    fd.append('storeName', form.value.storeName);
    if (storeId.value) {
      fd.append('storeId', storeId.value);
    }

    // 1. 上传证件信息
    const res = await fetch('http://121.43.176.9:8090/api/user-certification/upload-all', {
      method: 'POST',
      body: fd,
    }).then(r => r.json());

    if (res.code === 200) {
      // 后端upload-all接口已经自动更新了门店状态为6，无需再次调用
      const newStoreId = res.data?.storeId || storeId.value;
      if (newStoreId) {
        storeId.value = newStoreId;
      }
      ElMessage.success('证件信息上传成功，门店状态已更新');
      uploadAllSuccess.value = true;
      await fetchSetupPhotos();
    } else {
      ElMessage.error(res.msg || '上传失败');
      uploadAllSuccess.value = false;
    }
  } catch (e) {
    ElMessage.error('上传失败');
    uploadAllSuccess.value = false;
  } finally {
    isUploading.value = false;
  }
}

// 新增：上传外卖建店照片
async function uploadWaimaiPhotos() {
  if (!userId.value) {
    ElMessage.error('请先登录');
    return;
  }
  if (!uploadAllSuccess.value) {
    ElMessage.error('请先上传证件信息');
    return;
  }
  let hasPhoto = false;
  for (const type of [0,2,3]) {
    const files = allSetupPhotos.value[type] || [];
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (!file.url && file.raw) {
        hasPhoto = true;
        const fd = new FormData();
        fd.append('userId', userId.value);
        fd.append('photoType', type);
        fd.append('file', file.raw);
        const res = await fetch('http://121.43.176.9:8090/api/store-setup-photos/upload', {
          method: 'POST',
          body: fd,
        }).then(r => r.json());
        if (res.code === 200 && res.data) {
          files[i] = {
            name: file.name,
            url: res.data, // 后端返回的图片url
            status: 'success'
          };
        }
      }
    }
    allSetupPhotos.value[type] = [...files];
  }
  if (hasPhoto) {
    ElMessage.success('外卖建店照片上传完成');
    await fetchSetupPhotos();
  } else {
    ElMessage.info('没有需要上传的外卖建店照片');
  }
}
// 新增：上传团购建店照片
async function uploadTuangouPhotos() {
  if (!userId.value) {
    ElMessage.error('请先登录');
    return;
  }
  if (!uploadAllSuccess.value) {
    ElMessage.error('请先上传证件信息');
    return;
  }
  let hasPhoto = false;
  for (const type of [1,4]) {
    const files = allSetupPhotos.value[type] || [];
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (!file.url && file.raw) {
        hasPhoto = true;
        const fd = new FormData();
        fd.append('userId', userId.value);
        fd.append('photoType', type);
        fd.append('file', file.raw);
        const res = await fetch('http://121.43.176.9:8090/api/store-setup-photos/upload', {
          method: 'POST',
          body: fd,
        }).then(r => r.json());
        if (res.code === 200 && res.data) {
          files[i] = {
            name: file.name,
            url: res.data, // 后端返回的图片url
            status: 'success'
          };
        }
      }
    }
    allSetupPhotos.value[type] = [...files];
  }
  if (hasPhoto) {
    ElMessage.success('团购建店照片上传完成');
    await fetchSetupPhotos();
  } else {
    ElMessage.info('没有需要上传的团购建店照片');
  }
}

// 确认交接
async function confirmHandover() {
  if (!storeId.value) {
    ElMessage.error('无效的店铺ID');
    return;
  }
  // 这里假设有接口 /api/store/confirm-handover
  const res = await fetch('http://121.43.176.9:8090/api/store/confirm-handover', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ storeId: storeId.value, nextUser: nextUser.value }),
  }).then(r => r.json());
  if (res.code === 200) {
    ElMessage.success('交接成功');
    handoverConfirmed.value = true;
  } else {
    ElMessage.error(res.msg || '交接失败');
  }
}

// 确认交接逻辑，带上 nextUser
async function handleConfirmHandover() {
  // 验证所有必需的信息是否已上传
  const validationErrors = [];
  
  // 验证证件信息
  if (!form.value.storeName) {
    validationErrors.push('门店名称');
  }
  if (!form.value.businessLicenseArr || form.value.businessLicenseArr.length === 0) {
    validationErrors.push('营业执照');
  }
  if (!form.value.foodLicenseArr || form.value.foodLicenseArr.length === 0) {
    validationErrors.push('食品许可');
  }
  if (!form.value.idcardHandArr || form.value.idcardHandArr.length < 2) {
    validationErrors.push('手持身份证正反面（需要2张）');
  }
  if (!form.value.idcardArr || form.value.idcardArr.length < 2) {
    validationErrors.push('身份证正反面（需要2张）');
  }
  if (!form.value.storeFrontPhotoArr || form.value.storeFrontPhotoArr.length === 0) {
    validationErrors.push('门头照片');
  }
  if (!form.value.storeInsidePhotosArr || form.value.storeInsidePhotosArr.length === 0) {
    validationErrors.push('店内环境照片');
  }
  if (!form.value.storePhone) {
    validationErrors.push('门店联系电话');
  }
  if (!form.value.bankCardNumber) {
    validationErrors.push('银行卡号');
  }
  if (!form.value.bankPhone) {
    validationErrors.push('结算手机号');
  }
  
  // 验证建店照片
  const photoTypes = [0, 1, 2, 3, 4];
  for (const type of photoTypes) {
    const photos = allSetupPhotos.value[type] || [];
    if (photos.length === 0) {
      const typeLabel = getPhotoTypeLabel(type);
      validationErrors.push(`${typeLabel}建店照片`);
    }
  }
  
  // 验证交接人
  if (mustSelectNextUser.value && !nextUser.value) {
    validationErrors.push('下一个交接人');
  }
  
  if (validationErrors.length > 0) {
    ElMessage.error(`请完成以下信息上传：${validationErrors.join('、')}`);
    return;
  }
  
  await confirmHandover();
}

// 按钮可用性
const canSubmitWaimai = computed(() => waimaiPhotoTypes.every(t => waimaiPhotos.value[t] && waimaiPhotos.value[t].length > 0) && waimaiNextUser.value && uploadAllSuccess.value && !waimaiSubmitted.value);
const canSubmitTuangou = computed(() => tuangouPhotoTypes.every(t => tuangouPhotos.value[t] && tuangouPhotos.value[t].length > 0) && tuangouNextUser.value && uploadAllSuccess.value && !tuangouSubmitted.value);
const canConfirmHandover = computed(() => waimaiSubmitted.value && tuangouSubmitted.value && !handoverConfirmed.value);

// 检查是否可以上传证件信息
const canUploadBasicInfo = computed(() => {
  return form.value.storeName && 
    form.value.businessLicenseArr?.length > 0 &&
    form.value.foodLicenseArr?.length > 0 &&
    form.value.idcardHandArr?.length >= 2 &&
    form.value.idcardArr?.length >= 2 &&
    form.value.storeFrontPhotoArr?.length > 0 &&
    form.value.storeInsidePhotosArr?.length > 0 &&
    form.value.storePhone &&
    form.value.bankCardNumber &&
    form.value.bankPhone;
});

// 检查是否可以确认上传
const canConfirmUpload = computed(() => {
  // 检查证件信息是否完整
  const hasBasicInfo = form.value.storeName && 
    form.value.businessLicenseArr?.length > 0 &&
    form.value.foodLicenseArr?.length > 0 &&
    form.value.idcardHandArr?.length >= 2 &&
    form.value.idcardArr?.length >= 2 &&
    form.value.storeFrontPhotoArr?.length > 0 &&
    form.value.storeInsidePhotosArr?.length > 0 &&
    form.value.storePhone &&
    form.value.bankCardNumber &&
    form.value.bankPhone;
  
  // 检查建店照片是否完整
  const photoTypes = [0, 1, 2, 3, 4];
  const hasAllPhotos = photoTypes.every(type => {
    const photos = allSetupPhotos.value[type] || [];
    return photos.length > 0;
  });
  
  // 检查交接人（如果需要）
  const hasNextUser = !mustSelectNextUser.value || nextUser.value;
  
  return uploadAllSuccess.value && hasBasicInfo && hasAllPhotos && hasNextUser;
});

// 辅助
function getPhotoTypeLabel(type) {
  switch (type) {
    case 0: return '京东外卖';
    case 1: return '美团团购';
    case 2: return '美团外卖';
    case 3: return '饿了么外卖';
    case 4: return '抖音团购';
    default: return '';
  }
}
function parseUserIdFromToken(token) {
  if (!token) return null;
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload.userId || payload.userID || payload.userid || payload.sub || null;
  } catch {
    return null;
  }
}

onMounted(() => {
  fetchSetupPhotos();
});
</script> 